#include "front/front_interface.h"

using namespace std;
using namespace ppspeech;

// the last char of first word and the first char of second word is tone_three
vector<pair<string, string>> FrontEngineInterface::MergeThreeTones2(vector<pair<string, string>>& seg_result)
{
	vector<pair<string, string>> result;
	string word;
	string pos;
	vector<vector<string>> finals;  //韵母数组
	vector<string> word_final;
	vector<bool> merge_last(seg_result.size(), false);

	// 判断最后一个分词结果是不是标点
	int word_num = seg_result.size() - 1;
	if (find(mcPunctuation.begin(), mcPunctuation.end(), get<0>(seg_result[word_num])) == mcPunctuation.end()) {  // 最后一个分词结果不是标点
		word_num += 1;
	}

	// 获取韵母数组
	for (int i = 0; i < word_num; i++) {
		word_final = {};
		word = get<0>(seg_result[i]);
		pos = get<1>(seg_result[i]);
		// 如果是文字，则获取韵母，如果是可忽略的标点，例如引号，则跳过
		if (find(_punc_omit.begin(), _punc_omit.end(), word) ==
			_punc_omit.end()) {
			if (0 != GetFinals(word, &word_final)) {
				printf("ERROR: Frontend: Failed to get the final of word.\n");
			}
		}

		finals.push_back(word_final);
	}
	assert(word_num == finals.size());

	// 对第三声读音的字词分词结果进行处理
	for (int i = 0; i < word_num; i++) {
		word = get<0>(seg_result[i]);
		pos = get<1>(seg_result[i]);
		if (i - 1 >= 0 && !finals[i - 1].empty() &&
			absl::EndsWith(finals[i - 1].back(), "3") == true &&
			!finals[i].empty() &&
			absl::EndsWith(finals[i].front(), "3") == true &&
			!merge_last[i - 1]) {
			// if the last word is reduplication, not merge, because
			// reduplication need to be _neural_sandhi
			// seg_result[i - 1].first
			if (!IsReduplication(get<0>(seg_result[i - 1])) &&
				(ppspeech::utf8string2wstring(
					get<0>(seg_result[i - 1]))).length() + ppspeech::utf8string2wstring(word).length() <= 3) {
				result.back().first =
					result.back().first + get<0>(seg_result[i]);
				merge_last[i] = true;
			} else {
				result.push_back(make_pair(word, pos));
			}
		} else {
			result.push_back(make_pair(word, pos));
		}
	}

	//把标点的分词结果补上
	if (word_num < seg_result.size()) {
		result.push_back( make_pair(get<0>(seg_result[word_num]), get<1>(seg_result[word_num])) );
	}

	return result;
}
